package com.todo.auth.tool;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.todo.admin.common.base.SystemLoginUser;
import com.todo.auth.common.convert.UserAuthConvert;
import com.todo.common.common.constants.Constants;
import com.todo.common.common.entity.CurrentStaff;
import com.todo.common.common.entity.CurrentUser;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.common.common.exception.BizException;
import com.todo.common.utils.StringUtils;
import com.todo.component.redis.RedisService;
import io.jsonwebtoken.*;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author azhebuxing
 * @date 2025/2/19 23:47
 * @description
 */
@Component
@Slf4j
@Data
@RequiredArgsConstructor
public class TokenService {

    /**
     * 令牌前缀
     */
    public static final String LOGIN_USER_KEY = "login_user_key";
    /**
     * 令牌前缀
     */
    public static final String PREFIX = "Bearer ";

    private static final String CLAIM_KEY_USERNAME = "user_name";
    private static final String CLAIM_KEY_CREATED_TIME = "created_time";
    private static final String CLAIM_KEY_USER_TYPE = "user_type";

    private static final String CLAIM_VALUE_STAFF = "staff";
    private static final String CLAIM_VALUE_USER = "user";

    /**
     * 自定义令牌标识
     */
    @Value("${token.header}")
    private String header;

    /**
     * 令牌秘钥
     */
    @Value("${token.secret}")
    private String secret;

    /**
     * 自动刷新token的时间，当过期时间不足autoRefreshTime的值的时候，会触发刷新用户登录缓存的时间
     * 比如这个值是20,   用户是8点登录的， 8点半缓存会过期， 当过8.10分的时候，就少于20分钟了，便触发
     * 刷新登录用户的缓存时间
     */
    @Value("${token.autoRefreshTime}")
    private long autoRefreshTime;

    /**
     * 默认分钟
     */
    @Value("${token.tokenExpireTime}")
    private long tokenExpireTime;

    @Resource
    private RedisService redisService;

    /**
     * 判断是C端用户还是B端用户
     *
     * @param request
     * @return
     */
    public Boolean isTodoUser(HttpServletRequest request) {
        String token = getTokenFromRequest(request);
        if (StringUtils.isEmpty(token)) {
            throw new BizException(BizErrorCodeEnum.INVALID_ACCESS_TOKEN, "token is empty");
        }
        try {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String userType = (String) claims.get(CLAIM_KEY_USER_TYPE);
            return CLAIM_VALUE_USER.equals(userType);
        } catch (SignatureException | MalformedJwtException | UnsupportedJwtException |
                 IllegalArgumentException jwtException) {
            log.error("parse token failed.", jwtException);
            throw new BizException(BizErrorCodeEnum.INVALID_ACCESS_TOKEN, jwtException.getMessage());
        } catch (Exception e) {
            log.error("fail to get cached user from redis", e);
            throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST, e.getMessage());
        }
    }

    /**
     * 获取用户身份信息
     *
     * @param request
     * @return
     */
    public CurrentUser getCurrentUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getTokenFromRequest(request);
        if (StrUtil.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String username = (String) claims.get(LOGIN_USER_KEY);
                String logKey = String.format(Constants.LOGIN_USER_KEY, username);
                return JSONObject.parseObject(redisService.get(logKey), CurrentUser.class);
            } catch (MalformedJwtException | UnsupportedJwtException |
                     IllegalArgumentException jwtException) {
                log.error("parse token failed.", jwtException);
                throw new BizException(BizErrorCodeEnum.INVALID_ACCESS_TOKEN, jwtException.getMessage());
            } catch (Exception e) {
                log.error("fail to get cached user from redis", e);
                throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST, e.getMessage());
            }

        }
        return null;
    }

    /**
     * 获取员工身份信息
     *
     * @return 用户信息
     */
    public CurrentStaff getCurrentStaff(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getTokenFromRequest(request);
        if (StrUtil.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String username = (String) claims.get(LOGIN_USER_KEY);

                String logKey = String.format(Constants.LOGIN_STAFF_KEY, username);
                return JSONObject.parseObject(redisService.get(logKey), CurrentStaff.class);
            } catch (MalformedJwtException | UnsupportedJwtException |
                     IllegalArgumentException jwtException) {
                log.error("parse token failed.", jwtException);
                throw new BizException(BizErrorCodeEnum.INVALID_ACCESS_TOKEN, jwtException.getMessage());
            } catch (Exception e) {
                log.error("fail to get cached user from redis", e);
                throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST, e.getMessage());
            }

        }
        return null;
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createTokenAndPutUserInCache(SystemLoginUser loginUser) {
        loginUser.setCachedKey(IdUtil.fastUUID());

        String token = generateToken(loginUser, false);
        CurrentStaff currentStaff = UserAuthConvert.buildCurrentStaff(loginUser);
        currentStaff.setToken(token);

        String logKey = String.format(Constants.LOGIN_STAFF_KEY, loginUser.getUsername());
        redisService.set(logKey, JSONObject.toJSONString(currentStaff), Constants.LOGIN_USER_EXPIRE);

        return token;
    }

    /**
     * 当超过设置时间，自动刷新token
     *
     * @param currentStaff 登录用户
     */
//    public void refreshStaffToken(CurrentStaff currentStaff) {
//        long currentTime = System.currentTimeMillis();
//        if (currentTime > currentStaff.getAutoRefreshCacheTime()) {
//            loginUser.setAutoRefreshCacheTime(currentTime + TimeUnit.MINUTES.toMillis(autoRefreshTime));
//            // 根据uuid将loginUser存入缓存
//            String logKey = String.format(Constants.LOGIN_STAFF_KEY, loginUser.getUsername());
//            redisService.set(logKey, JSONObject.toJSONString(loginUser));
//        }
//    }


    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String generateToken(Map<String, Object> claims) {
        long now = (new Date()).getTime();
        Date expiryDate = new Date(now + tokenExpireTime * 60 * 1000); // validityInMilliseconds是token的有效时间
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * 根据用户信息生成token
     *
     * @param userDetails
     * @param isUser      是否C端用户
     * @return
     */
    public String generateToken(UserDetails userDetails, Boolean isUser) {

        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED_TIME, new Date());
        if (isUser) {
            claims.put(CLAIM_KEY_USER_TYPE, CLAIM_VALUE_USER);
        } else {
            claims.put(CLAIM_KEY_USER_TYPE, CLAIM_VALUE_STAFF);
        }
        return generateToken(claims);
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }


    /**
     * 获取请求token
     *
     * @return token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StrUtil.isNotEmpty(token) && token.startsWith(PREFIX)) {
            token = StrUtil.stripIgnoreCase(token, PREFIX, null);
        }
        return token;
    }

}
